<template>
  <div class="home-container">
    <div class="record-container">
      <div class="record-log-item" v-for="(item,index) in logRecords" :key="item">
        <div class="record-log-item-title">{{ item.rq }}</div>
        <div class="log-children">
          <div class="log-row" v-for="(it,i) in item.logsDetailList" :key="i">
            <div class="log-i">{{ i + 1 }}</div>
            <div class="log-t">{{ { 1: '上午', 2: '下午', 3: '晚上' }[it.rqType] }}:</div>
            <div class="log-c">{{ it.workContent }}</div>
          </div>
          <div v-if="!item.logsDetailList || item.logsDetailList.length===0">未填写</div>
        </div>
        <div class="log-summary">
          {{ item.summaryDayWork || '未填写' }}
        </div>
      </div>
    </div>
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="form.rq"
          is-link
          readonly
          name="picker"
          label="日期"
          required
          placeholder="点击选择日期"
          @click="showPicker = true"
        />
        <van-collapse v-model="activeNames">
          <van-collapse-item name="1">
            <template #title>
              <div>事项
                <van-icon name="add" @click.stop="handleShowAddItemForm(undefined)" />
              </div>
            </template>
            <van-swipe-cell v-for="(item,index) in form.logsDetailList" :key="index">
              <div class="logs-item" @click="handleShowAddItemForm(index)">
                <div class="logs-item-row">
                  <div class="logs-item-row-hd"> 时间:</div>
                  <div class="logs-item-row-bd">
                    {{ { 1: '上午', 2: '下午', 3: '晚上' }[item.rqType] }}
                  </div>
                </div>
                <div class="logs-item-row">
                  <div class="logs-item-row-hd"> 内容:</div>
                  <div class="logs-item-row-bd">{{ item.workContent }}</div>
                </div>
              </div>
              <template #right>
                <van-button square type="danger" text="删除" class="delete-button" @click="handleDel(index)"/>
              </template>
            </van-swipe-cell>
          </van-collapse-item>
        </van-collapse>
        <van-field
          v-model="form.summaryDayWork"
          type="textarea"
          name="总结"
          label="总结"
          placeholder="总结"
        />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
    <van-popup v-model:show="showPicker" position="bottom">
      <van-date-picker
        v-model="date"
        @confirm="onConfirm" @cancel="showPicker = false" :max-date="maxDate" :minDate="minDate" />
    </van-popup>
    <van-popup v-model:show="showLogItemForm" :style="{ padding: '5px' }"
               position="bottom"
    >
      <van-form @submit="handleAddItemToForm" label-width="80px">
        <div class="log-item-form-header">
          <div class="log-item-form-header-hd" @click="showLogItemForm=false">取消</div>
          <div class="log-item-form-header-bd"></div>
          <div class="log-item-form-header-ft">
            <van-button type="primary" native-type="handleAddItemToForm" size="mini">
              确定
            </van-button>
          </div>
        </div>
        <van-cell-group>
          <van-field name="radio" label="时间">
            <template #input>
              <van-radio-group label="时间" v-model="logItem.rqType" direction="horizontal">
                <van-radio name="1">上午</van-radio>
                <van-radio name="2">下午</van-radio>
                <van-radio name="3">晚上</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            v-model="logItem.workContent"
            name="workContent"
            label="内容"
            placeholder="内容"
            type="textarea"
            required
            :rules="[{ required: true, message: '请填写内容' }]"
          />
          <!--<van-field-->
          <!--  v-model="logItem.workResult"-->
          <!--  name="workResult"-->
          <!--  label="结果"-->
          <!--  type="textarea"-->
          <!--  placeholder="结果"-->
          <!--  required-->
          <!--  :rules="[{ required: true, message: '请填写内容' }]"-->
          <!--/>-->
          <!--<van-field name="switch" label="是否完成">-->
          <!--  <template #input>-->
          <!--    <van-switch v-model="logItem.completed" size="15px"/>-->
          <!--  </template>-->
          <!--</van-field>-->
        </van-cell-group>
      </van-form>
    </van-popup>

  </div>
</template>

<script setup>

import { onMounted, reactive, ref, toRaw, watch } from 'vue'
import dayjs from 'dayjs'
import { addContentApi, getDetailByDayApi, myCompleteLogsApi, updateContentApi } from '@/api/workLog.js'
import { showToast } from 'vant'
import { useRoute, useRouter } from 'vue-router'
import useUserStore from '@/stores/user.js'

const route = useRoute()
const router = useRouter()
const editLogItemIndex = ref(0)
const showLogItemForm = ref(false)
const showPicker = ref(false)
const activeNames = ref(['1'])
const maxDate = ref(new Date())
const minDate = ref(new Date(dayjs().subtract(1, 'day').format('YYYY-MM-DD')))
const date = ref([
  dayjs().year(),
  dayjs().month() + 1,
  dayjs().day()
])
const form = reactive({
  id: '',
  rq: dayjs().format('YYYY-MM-DD'),
  summaryDayWork: '',
  logsDetailList: []
})
const logItem = reactive({
  rqType: '1',
  workContent: '',
  workResult: '',
  completed: ''
})
const logRecords = ref([])
const updateLoading = ref(false)

const userStore = useUserStore()


watch(() => form.rq, () => {
  getLogDetail()
  getLogs()
})

const getLogs = () => {
  logRecords.value = []
  let params = {
    rq: dayjs(form.rq).format('YYYY-MM'),
    createBy: userStore.userInfo.userId,
    pageSize: 1000,
    pageNum: 1
  }
  myCompleteLogsApi(params).then(res => {
    logRecords.value = res.rows
  })
}

const onConfirm = ({ selectedValues }) => {
  form.rq = selectedValues.join('/')
  showPicker.value = false
}

const handleAddItemToForm = () => {
  if (logItem.rqType && logItem.workContent) {
    if(editLogItemIndex.value===undefined){
      // 新增
      form.logsDetailList.push({ ...logItem })
    }else{
      // 编辑
      form.logsDetailList[editLogItemIndex.value] = { ...logItem }
    }
    logItem.rqType = '1'
    logItem.workContent = ''
    logItem.workResult = ''
    logItem.completed = ''
    showLogItemForm.value = false
  }
}
const handleDel = (index)=>{
  form.logsDetailList.splice(index,1)
}
const handleShowAddItemForm = (index) => {
  editLogItemIndex.value = index
  if (index === undefined) {
    // 新增
    logItem.rqType = '1'
    logItem.workContent = ''
    logItem.workResult = ''
    logItem.completed = ''
    showLogItemForm.value = true
  } else {
    // 编辑
    logItem.rqType = form.logsDetailList[index].rqType
    logItem.workContent = form.logsDetailList[index].workContent
    logItem.workResult = form.logsDetailList[index].workResult
    logItem.completed = form.logsDetailList[index].completed
    showLogItemForm.value = true
  }
}
const onSubmit = () => {
  if(updateLoading.value)return
  updateLoading.value = true
  let params = toRaw(form)
  params.rq = dayjs(params.rq).format('YYYY-MM-DD')
  params.logsDetailList = params.logsDetailList.map(item => {
    item.completed = item.completed ? 12 : 1
    return item
  })

  updateContentApi(form).then(() => {
    updateLoading.value = false
    showToast('操作成功')
    router.back()
  }).catch(err => {
    updateLoading.value = false
    showToast(err.msg)
  })
  // if (params.id) {
  //   // 更新
  //   updateContentApi(form).then(() => {
  //     showToast('操作成功')
  //     router.back()
  //   }).catch(err => {
  //     showToast(err.msg)
  //   })
  // } else {
  //   // 新增
  //   delete params.id
  //   addContentApi(form).then(() => {
  //     showToast('操作成功')
  //     getLogDetail()
  //     router.back()
  //   }).catch(err => {
  //     showToast(err.msg)
  //   })
  // }
}

const getLogDetail = () => {
  getDetailByDayApi(form.rq).then(res => {
    if (res && res.data) {
      date.value = [
        dayjs(res.data.rq).year(),
        dayjs(res.data.rq).month() + 1,
        dayjs(res.data.rq).day()
      ]
      form.rq = dayjs(res.data.rq).format('YYYY-MM-DD')
      form.id = res.data.id
      form.summaryDayWork = res.data.summaryDayWork
      form.logsDetailList = res.data.logsDetailList.map(item => {
        item.completed = item.completed === 12
        return item
      })
    } else {
      form.id = ''
      form.summaryDayWork = ''
      form.logsDetailList = []
    }
  })
}

onMounted(() => {
  if (route.query.date) {
    form.rq = route.query.date
  }
  getLogDetail()
  getLogs()
})

</script>

<style scoped lang="less">
.home-container {
  min-height: 100%;
  padding-top: 10px;

  .record-container {
    //height: 40vh;
    //overflow-y: auto;
    margin-bottom: 10px;

    .record-log-item {
      width: calc(100% - 32px);
      background-color: #fff;
      margin: 0 16px 10px;
      border-radius: 5px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

      .record-log-item-title {
        height: 40px;
        line-height: 40px;
        padding: 0 10px;
        border-bottom: 1px solid #f2f2f2;
        font-weight: bold;
      }

      .log-children {
        line-height: 20px;
        padding: 10px;
        border-bottom: 1px solid #f2f2f2;

        .log-row {
          margin-bottom: 5px;
          display: flex;
          line-height: 20px;

          .log-i {
            width: 20px;
            height: 20px;
            background-color: #f2f2f2;
            text-align: center;
          }

          .log-t {
            width: 40px;
            text-align: center;
          }

          .log-c {
            width: calc(100% - 70px);
          }
        }
      }

      .log-summary {
        padding: 10px;
      }
    }
  }

  .logs-item {
    border: 1px solid #eee;
    padding: 5px;
    border-radius: 5px;
    overflow: hidden;
    margin-bottom: 10px;
    box-sizing: border-box;

    .logs-item-row {
      display: flex;

      .logs-item-row-hd {
        width: 40px;
      }

      .logs-item-row-bd {
        width: calc(100% - 50px);
        overflow: hidden;
      }
    }
  }

  .delete-button {
    height: 100%;
  }

  .log-item-form-header {
    height: 40px;
    display: flex;
    align-items: center;
    margin-bottom: 5px;

    .log-item-form-header-bd {
      flex: 1;
    }

    .log-item-form-header-hd {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 5px;
      color: #999;
    }

    .log-item-form-header-ft {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 5px;
      color: rgb(65, 135, 242);
    }
  }
}

</style>
